package com.zbbt.sportslottery.ui.activity;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.zbbt.sportslottery.R;
import com.zbbt.sportslottery.app.App;
import com.zbbt.sportslottery.app.Constant;
import com.zbbt.sportslottery.app.ServerConfig;
import com.zbbt.sportslottery.bean.ProtalOrders;
import com.zbbt.sportslottery.bean.SuperResult;
import com.zbbt.sportslottery.net.TypeGsonHttpHandler;
import com.zbbt.sportslottery.net.ZbHttpClient;
import com.zbbt.sportslottery.ui.adapter.ElevenGridAdapter;
import com.zbbt.sportslottery.ui.adapter.ElevenGridAdapter.CallBackEleven;
import com.zbbt.sportslottery.ui.widget.swipe.SwipeRefreshLayout;
import com.zbbt.sportslottery.ui.widget.swipe.SwipeRefreshLayout.OnRefreshListener;
import com.zbbt.sportslottery.util.LogUtil;
import com.zbbt.sportslottery.util.SharePreferUtil;
import com.zbbt.sportslottery.util.ToastUtil;
import com.zbbt.sportslottery.util.UmengUtil;

/**
 * 
 * @ClassName: ElevenWebViewActivity
 * @Description: 11选5走势图
 * @author：mingShuo
 * @date：2015年7月16日 上午11:24:18
 * @version V1.0
 */
public class ElevenWebViewActivity extends SimpleBaseActivity {
	private LayoutInflater mInflater;
	// private LinearLayout elevenChartLayout;
	private SwipeRefreshLayout mSwipeRefreshLayout;
	private WebView mWebView;
	private int type = 0;
	private String url;
	private String urlname;
	private boolean isError = false;
	private LinearLayout none_view_layout;// 无网络时 显示的界面

	PopupWindow popWindow;
	Boolean[] checked;
	public int defalutCheck = 0;// 默认玩法选择第一项
	ElevenGridAdapter elevenadapter;
	public boolean isOpenPop = false;
	private Toolbar top;
	private LinearLayout error_layout;
	private int openNum;
	private TextView tv_right;
	private List<ProtalOrders> protals = new ArrayList<ProtalOrders>();

	@Override
	public void onResume() {
		super.onResume();
		if (openNum == 1) {
			tv_right.setVisibility(View.VISIBLE);
			// tv_right.setBackgroundResource(R.drawable.selector_zoushi_11x5);
		}
	}

	@Override
	protected void setListener() {
		error_layout.setOnClickListener(this);
	}

	@Override
	protected void onClickEvent(View v) {

		switch (v.getId()) {
		case R.id.error_layout:
			mSwipeRefreshLayout.setVisibility(View.VISIBLE);
			mSwipeRefreshLayout.setRefreshing(true);
			isError = false;
			error_layout.setVisibility(View.GONE);
			mWebView.reload();
			break;
		case R.id.tv_right:
			if (protals.size() > 0) {
				changPopState(tv_right, true);
			} else {
				ToastUtil.showShort("暂无更多图表");
			}
			break;

		default:
			break;
		}
	}

	@Override
	protected void initData() {

	}

	public void changPopState(View v, boolean flag) {
		isOpenPop = !isOpenPop;
		if (isOpenPop) {
			// Drawable nav_up =
			// getResources().getDrawable(R.drawable.open);
			// nav_up.setBounds(0, 0, nav_up.getMinimumWidth(),
			// nav_up.getMinimumHeight());
			// titView.setCompoundDrawables(null, null, nav_up, null);
			popAwindow(v);
			// WindowManager.LayoutParams lp =
			// getActivity().getWindow().getAttributes();
			// lp.alpha = 0.7f;
			// getActivity().getWindow().setAttributes(lp);
		} else {
			if (popWindow != null) {
				WindowManager.LayoutParams lp = getWindow().getAttributes();
			}
		}
	}

	@SuppressLint("NewApi")
	private void popAwindow(View parent) {
		type = SharePreferUtil.getInt("chart_num", 0);
		checked = new Boolean[protals.size()];
		for (int i = 0; i < protals.size(); i++) {
			checked[i] = false;
		}
		checked[type] = true;
		View v = View.inflate(context, R.layout.list_pop_eleven, null);
		// GridView 可以添加其他的自己View进来 android:numColumns="4"可设定每行所添加的个数
		GridView gView = (GridView) v.findViewById(R.id.elevengrid);

		// new CallBackEleven() 在adapter中操作监听的回调
		elevenadapter = new ElevenGridAdapter(this, checked, protals, new CallBackEleven() {
			@Override
			public void showChange(int position, boolean isChecked) {
				if (position == 0) {
					// 基本走势
					UmengUtil.onEvent(context, Constant.UMENG_EVLENT_JBZS);
				} else if (position == 1) {
					// 好吗分布
					UmengUtil.onEvent(context, Constant.UMENG_EVLENT_HMFB);
				} else if (position == 2) {
					// 前一直选
					UmengUtil.onEvent(context, Constant.UMENG_EVLENT_QYZHIX);
				} else if (position == 3) {
					// 前二直选
					UmengUtil.onEvent(context, Constant.UMENG_EVLENT_QEZHIX);
				} else if (position == 4) {
					// 前三直选
					UmengUtil.onEvent(context, Constant.UMENG_EVLENT_QSZHIX);
				} else if (position == 5) {
					// 前二组选
					UmengUtil.onEvent(context, Constant.UMENG_EVLENT_QEZUX);
				} else if (position == 6) {
					// 前三组选
					UmengUtil.onEvent(context, Constant.UMENG_EVLENT_QSZUX);
				}

				if (isChecked) {
					// 单选
					for (int i = 0; i < checked.length; i++) {
						checked[i] = false;
					}
					checked[position] = true;
					elevenadapter.notifyDataSetChanged();
					changeload(position);
					popWindow.dismiss();
				} else {// 当点击相同的item时 所出发的事件
					checked[position] = true;
					elevenadapter.notifyDataSetChanged();
					changeload(position);
					popWindow.dismiss();
				}
			}
		});
		gView.setAdapter(elevenadapter);
		// 选择弹出的形式 popWindow大小可在布局中设定
		gView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		popWindow = new PopupWindow(v);
		popWindow.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
		popWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
		popWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.popupwindow_bg));
		popWindow.setFocusable(true);
		popWindow.setOutsideTouchable(false);
		popWindow.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				isOpenPop = false;
			}
		});

		// 设置PopupWindow弹出和关闭动画
		popWindow.setAnimationStyle(R.style.PopupAnimation);
		int[] location = new int[2];
		int tH = 0;
		if (top != null && top instanceof View) {
			// 设置弹出的pop的位置
			Rect r = new Rect();
			top.getLocalVisibleRect(r);// 返回一个填充的Rect对象，
										// 感觉是这个View的Rect大小，left，top取到的都是0
			top.getGlobalVisibleRect(r);// 获取全局坐标系的一个视图区域，
										// 返回一个填充的Rect对象；该Rect是基于总整个屏幕的
			top.getLocationInWindow(location);
			tH = top.getHeight();
			top.getLocationOnScreen(location);
		}
		popWindow.showAtLocation(parent, Gravity.CENTER_HORIZONTAL | Gravity.TOP, location[0] - 100,
				location[1] + tH);
		popWindow.update();
	}

	// 保存右侧所选择的的选项
	protected void changeload(int postion) {
		if (postion == 0) {
			tv_right.setText(urlname);
			mWebView.loadUrl(url + "?appid=" + App.PARAM_APPID);
		} else {
			tv_right.setText(protals.get(postion).getProductName());
			mWebView.loadUrl(protals.get(postion).getProductUrl() + "?appid=" + App.PARAM_APPID);
		}
		SharePreferUtil.putInt("chart_num", postion);
	}

	@Override
	protected void onActivityCreated(Bundle savedInstanceState) {
		setContentView(R.layout.fragment_eleven_web_view);
		error_layout = (LinearLayout) findViewById(R.id.error_layout);
		Intent intent = getIntent();
		openNum = intent.getIntExtra("isOpen", 0);
		url = intent.getStringExtra("evelentUrl");
		urlname = intent.getStringExtra("evelname");
		LogUtil.printD("openNum", openNum + "???");
	}

	@Override
	protected void initView() {
		if (openNum == 1) {
			getSelectWebURL();
			SharePreferUtil.putInt("chart_num", 0);
			LogUtil.printD("openNum", openNum + "111");
			setTitle("11选5走势图");
			top = (Toolbar) findViewById(R.id.toolbar);
			mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
			mWebView = (WebView) findViewById(R.id.frag_webview);
			tv_right = (TextView) findViewById(R.id.tv_right);
			mWebView.requestFocus();
			mWebView.getSettings().setJavaScriptEnabled(true);
			initToolBar();

			// 当前页面加载
			mWebView.setWebViewClient(new WebViewClient() {
				@Override
				public void onPageStarted(WebView view, String url, Bitmap favicon) {
					mSwipeRefreshLayout.setRefreshing(true);
					super.onPageStarted(view, url, favicon);
				}

				@Override
				public void onPageFinished(WebView view, String url) {
					mSwipeRefreshLayout.setRefreshing(false);
					super.onPageFinished(view, url);
				}

				@Override
				public boolean shouldOverrideUrlLoading(WebView view, String url) {
					mWebView.loadUrl(url);
					return true;
				}

				@Override
				public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
					view.loadUrl("javascript:document.body.innerHTML=\"" + "" + "\"");
					ToastUtil.showShort("网络连接失败,请稍后再试！");
					error_layout.setVisibility(View.VISIBLE);
					super.onReceivedError(view, errorCode, description, failingUrl);
					isError = true;
				}

			});
			mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {

				@Override
				public void onRefresh() {
					mWebView.reload();
				}
			});
			// 默认的加载选项
			// type = SharePreferUtil.getInt("chart_num", 0);
			// checked = new Boolean[eleven.length];
			// for (int i = 0; i < eleven.length; i++) {
			// checked[i] = false;
			// }
			// checked[type] = true;
			changeload(0);
		} else {
			LogUtil.printD("openNum", openNum + "222");
			none_view_layout = (LinearLayout) findViewById(R.id.none_view_layout);
			none_view_layout.setVisibility(View.VISIBLE);
			setTitle("走势图");
		}
	}

	// 获取七组数据
	private void getSelectWebURL() {
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("productType", 1);
		ZbHttpClient.postNewApi(ServerConfig.API_PROTAL_ORDERS, jsonObject,
				new TypeGsonHttpHandler<SuperResult<ProtalOrders>>(true) {

					@Override
					public void onSuccess(SuperResult<ProtalOrders> data) {
						protals.addAll(data.getData());
					}

					@Override
					public void onFailure(String errorCode, String errorMsg) {

					}

				});
	}
}
